import { useState } from "react";

export default function Fruits() {
  const [fruits, setFruits] = useState(["Apple", "Bananas", "Orange"]);

  const handleAddFruit = () => {
    const inputEl = document.getElementById("fruitInput");
    if (inputEl.value.trim() !== "") {
      // 防止后面清空inputEl.value的时候影响到setFruits的更新
      // 由于更新函数具有延迟性
      const value = inputEl.value;
      setFruits((f) => [...f, value]);
    }
    inputEl.value = ""; // empty input
  };

  const handleDeleteFruit = (index) =>
    setFruits((f) => f.filter((_, i) => i !== index));

  const listItems = fruits.map((fruit, index) => (
    <li key={index} onClick={() => handleDeleteFruit(index)}>
      {fruit}
    </li>
  ));
  return (
    <>
      <h2>List of Fruits</h2>
      <ul>{listItems}</ul>

      <input id="fruitInput" type="text" placeholder="Enter fruit name" />
      <button onClick={handleAddFruit}>Add Fruit</button>
    </>
  );
}
